<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input v-model="queryParams.couponName" placeholder="请输入优惠券名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="折扣类型" prop="discountType">
        <el-select style="width: 188px;" v-model="queryParams.discountType" placeholder="请选择折扣类型" clearable>
          <el-option v-for="dict in cf_coupon_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否适用于所有商品" prop="validForAllProducts" label-width="150px">
        <el-select style="width: 198px;" v-model="queryParams.validForAllProducts" placeholder="是否适用于所有商品" clearable>
          <el-option v-for="dict in cf_coupon_is_specific" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="过期日期" prop="expirationDate">
        <el-date-picker clearable v-model="queryParams.expirationDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择过期日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['coffee:coupon:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['coffee:coupon:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['coffee:coupon:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['coffee:coupon:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="couponId" />
      <el-table-column width="160" label="优惠券名称" align="center" fixed prop="couponName" />
      <el-table-column label="折扣类型" align="center" prop="discountType">
        <template #default="scope">
          <dict-tag :options="cf_coupon_type" :value="scope.row.discountType" />
        </template>
      </el-table-column>
      <el-table-column label="折扣值" align="center" prop="discountValue" />
      <el-table-column width="180" label="优惠券所需的最低订单金额" align="center" prop="minimumOrderAmount" />
      <el-table-column label="总发放数量" align="center" prop="totalQuantity" />
      <el-table-column width="180" label="剩余可领取数量" align="center" prop="remainingQuantity" />
      <el-table-column width="180" label="是否适用于所有商品" align="center" prop="validForAllProducts">
        <template #default="scope">
          <dict-tag :options="cf_coupon_is_specific" :value="scope.row.validForAllProducts" />
        </template>
      </el-table-column>
      <el-table-column width="180" label="适用特定商品ID列表" align="center" prop="specificProductIds" />
      <el-table-column label="过期日期" align="center" prop="expirationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['coffee:coupon:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['coffee:coupon:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改优惠券信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="折扣类型" prop="discountType">
          <el-select v-model="form.discountType" placeholder="请选择折扣类型">
            <el-option v-for="dict in cf_coupon_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣值" prop="discountValue">
          <el-input v-model="form.discountValue" placeholder="请输入折扣值" />
        </el-form-item>
        <el-form-item label="优惠券所需的最低订单金额" prop="minimumOrderAmount">
          <el-input v-model="form.minimumOrderAmount" placeholder="请输入使用该优惠券所需的最低订单金额" />
        </el-form-item>
        <el-form-item label="总发放数量" prop="totalQuantity">
          <el-input v-model="form.totalQuantity" placeholder="请输入总发放数量" />
        </el-form-item>
        <el-form-item label="剩余可领取数量" prop="remainingQuantity">
          <el-input v-model="form.remainingQuantity" placeholder="请输入剩余可领取数量" />
        </el-form-item>
        <el-form-item label="是否适用于所有商品" prop="validForAllProducts">
          <el-radio-group v-model="form.validForAllProducts">
            <el-radio v-for="dict in cf_coupon_is_specific" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="过期日期" prop="expirationDate">
          <el-date-picker clearable v-model="form.expirationDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择过期日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/coffee/coupon";

const { proxy } = getCurrentInstance();
const { cf_coupon_is_specific, cf_coupon_type } = proxy.useDict('cf_coupon_is_specific', 'cf_coupon_type');

const couponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    couponName: null,
    discountType: null,
    validForAllProducts: null,
    expirationDate: null,
  },
  rules: {
    couponName: [
      { required: true, message: "优惠券名称不能为空", trigger: "blur" }
    ],
    discountType: [
      { required: true, message: "折扣类型不能为空", trigger: "change" }
    ],
    discountValue: [
      { required: true, message: "折扣值不能为空", trigger: "blur" }
    ],
    totalQuantity: [
      { required: true, message: "总发放数量不能为空", trigger: "blur" }
    ],
    remainingQuantity: [
      { required: true, message: "剩余可领取数量不能为空", trigger: "blur" }
    ],
    validForAllProducts: [
      { required: true, message: "是否适用于所有商品不能为空", trigger: "change" }
    ],
    expirationDate: [
      { required: true, message: "过期日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询优惠券信息列表 */
function getList () {
  loading.value = true;
  listCoupon(queryParams.value).then(response => {
    couponList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel () {
  open.value = false;
  reset();
}

// 表单重置
function reset () {
  form.value = {
    couponId: null,
    couponName: null,
    discountType: null,
    discountValue: null,
    minimumOrderAmount: null,
    totalQuantity: null,
    remainingQuantity: null,
    validForAllProducts: null,
    specificProductIds: null,
    expirationDate: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("couponRef");
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.couponId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd () {
  reset();
  open.value = true;
  title.value = "添加优惠券信息";
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset();
  const _couponId = row.couponId || ids.value
  getCoupon(_couponId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改优惠券信息";
  });
}

/** 提交按钮 */
function submitForm () {
  proxy.$refs["couponRef"].validate(valid => {
    if (valid) {
      if (form.value.couponId != null) {
        updateCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _couponIds = row.couponId || ids.value;
  proxy.$modal.confirm('是否确认删除优惠券信息编号为"' + _couponIds + '"的数据项？').then(function () {
    return delCoupon(_couponIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('coffee/coupon/export', {
    ...queryParams.value
  }, `coupon_${new Date().getTime()}.xlsx`)
}

getList();
</script>
